//
//  AppDelegate.c
//  LearnC
//
//  Created by 劉裕 on 10/10/2016.
//  Copyright © 2016 劉裕. All rights reserved.
//

#include <CoreGraphics/CoreGraphics.h>
#include <objc/runtime.h>
#include <objc/message.h>

struct AppDelegate {
    Class isa;
    id window;
};

Class AppDelegateClass;

BOOL applicationDidFinishLaunchingWithOptions(
        struct AppDelegate *self, SEL _cmd, void *application, void *options) {
    self->window = objc_msgSend((id) objc_getClass("UIWindow"), sel_getUid("alloc"));
    self->window = objc_msgSend(self->window, sel_getUid("initWithFrame:"),
            (struct CGRect) {0, 0, 320, 568});
    id viewController = objc_msgSend(
            objc_msgSend((id) objc_getClass("UIViewController"), sel_getUid("alloc")),
            sel_getUid("init"));
    id view = objc_msgSend(
            objc_msgSend((id) objc_getClass("View"), sel_getUid("alloc")),
            sel_getUid("initWithFrame:"),
            (struct CGRect) {0, 0, 320, 568});
    objc_msgSend(objc_msgSend(viewController, sel_getUid("view")), sel_getUid("addSubview:"), view);
    objc_msgSend(self->window, sel_getUid("setRootViewController:"), viewController);
    objc_msgSend(self->window, sel_getUid("makeKeyAndVisible"));

    return YES;
}

__attribute__((constructor))
static void initAppDelegate() {
    AppDelegateClass = objc_allocateClassPair((Class) objc_getClass("UIResponder"), "AppDelegate", 0);
    class_addIvar(AppDelegateClass, "window", sizeof(id), 0, "@");
//    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    class_addMethod(AppDelegateClass, sel_registerName("application:didFinishLaunchingWithOptions:"), (IMP) applicationDidFinishLaunchingWithOptions, "i@:@@");
    objc_registerClassPair(AppDelegateClass);
}